import clone from 'lodash/clone';
import { notification } from 'antd';
import {
    query as queryUsers,
    // queryCurrent,
    queryUserInfo,
    getPersonalPortrait,
    saveorupdate,
    getEntryUserByUserCode,
    uploademployeeavatar,
    updateemployeeavatar
} from '@/services/user';
import { fetchMailBindInfo, fetchMailBindTemplates } from '@/services/mail';

export default {
    namespace: 'user',

    state: {
        list: [],
        currentUser: {},
        avatarFile: {},
        entryUser: {},
        mailBindList: [],
        mailBindTemplates: []
    },

    effects: {
        *fetch(_, { call, put }) {
            const response = yield call(queryUsers);
            yield put({
                type: 'save',
                payload: response
            });
        },
        *fetchCurrent({ payload, callback }, { call, put }) {
            const response = yield call(queryUserInfo, payload);
            // 假如是首次登陆的时候把接口返回的数据写入进currennt
            if (response.code === 20012 || response.code === 20013) {
                const data = clone(response.data);
                data.isInit = true; // 用户首次登陆判断字段
                data.code = response.code; // 用户首次登陆的code，用于判断当前状态
                if (callback) callback(data);
                yield put({
                    type: 'saveCurrentUser',
                    payload: data
                });
            }
            const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
            if (response.code === 10000) {
                localStorage.setItem(
                    'user',
                    JSON.stringify({
                        ...currentUser,
                        ...response.data,
                        // 如果部门 id 返回空或者 -1，则不应该填入
                        departmentId: response.data.departmentId >= 0 ? response.data.departmentId : undefined
                    })
                );
                if (callback) callback(response.data);
                yield put({
                    type: 'saveCurrentUser',
                    payload: { ...currentUser, ...response.data }
                });
            }
        },
        *fetchPersonalPortrait(_, { call, put }) {
            const response = yield call(getPersonalPortrait);
            if (response.code === 10000) {
                yield put({
                    type: 'saveAvatarFile',
                    payload: response.data
                });
            } else {
                notification.error({
                    message: `请求错误 ${response.msg}`
                });
            }
            return response;
        },
        *fetchUpdate({ payload, callback }, { call }) {
            const response = yield call(saveorupdate, payload);
            if (callback) callback(response);
        },
        *fetchEntryUser({ payload }, { call, put }) {
            const response = yield call(getEntryUserByUserCode, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'saveEntryUser',
                    payload: response.data
                });
            }
        },
        /**
         * 上传个人头像
         */
        *uploademployeeavatar({ payload, callback }, { call }) {
            const response = yield call(uploademployeeavatar, payload);
            callback(response);
        },
        /**
         * 更新个人头像
         */
        *updateemployeeavatar({ payload, callback }, { call }) {
            const response = yield call(updateemployeeavatar, payload);
            callback(response);
        },
        // 获取绑定邮箱列表
        *fetchMailBindInfo({ payload, callback }, { call, put }) {
            const response = yield call(fetchMailBindInfo, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'saveOther',
                    payload: {
                        mailBindList: response.data
                    }
                });
                // 当前使用的邮箱，前端维护一套当前访问的邮箱
                if (!localStorage.getItem('currentMail') && response.data[0]) {
                    yield localStorage.setItem('currentMail', response.data[0].email);
                }
            }
            if (callback) callback(response);
        },
        // 获取可使用的邮箱服务
        *fetchMailBindTemplates({ payload }, { call, put }) {
            const response = yield call(fetchMailBindTemplates, payload);
            if (response.code === 10000) {
                yield put({
                    type: 'saveOther',
                    payload: {
                        mailBindTemplates: response.data
                    }
                });
            }
        },
        // 如果有触及到头像更新的，因为头像的内容存储在modal里，所以得额外处理
        *fixAvatarFile({ payload }, { put }) {
            console.log(payload, 'payload');
            yield put({
                type: 'saveAvatarFile',
                payload
            });
        }
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                list: action.payload
            };
        },
        saveCurrentUser(state, action) {
            return {
                ...state,
                currentUser: action.payload || {}
            };
        },
        saveAvatarFile(state, action) {
            return {
                ...state,
                avatarFile: action.payload || {}
            };
        },
        changeNotifyCount(state, action) {
            return {
                ...state,
                currentUser: {
                    ...state.currentUser,
                    notifyCount: action.payload.totalCount,
                    unreadCount: action.payload.unreadCount
                }
            };
        },
        saveEntryUser(state, action) {
            return {
                ...state,
                entryUser: action.payload || {}
            };
        },
        saveOther(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        }
    }
};
